//
//  ST_SimilarLoginViewController.swift
//  btvideo
//
//  Created by mac on 2021/3/16.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyUserDefaults
import SwiftyJSON
import MBProgressHUD
import RxCocoa
import RxSwift


class ST_SimilarLoginViewController: UIViewController {
    
    
    //    MARK: - Life cycle
    deinit {
        print("【bug QQ登录多次创建对象bug】 ST_SimilarLoginViewController deinit")
    }
    
    fileprivate var pageName:String?{
        didSet{
            
            guard let p = pageName else { return  }
            
            MobClick.beginLogPageView(p)
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        guard let p = pageName else { return  }
        
        MobClick.endLogPageView(p)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom+200, right: 0))
        }
        
        view.addSubview(gradient_view)
        gradient_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom)
            make.height.equalTo(488)
        }
        
        binding()
        
    }
    
    
    private func binding(){
        
        
        self.licenceVC.agreeObserver.withUnretained(self).subscribe(onNext: { own,f in
            
            CLShanYanSDKManager.initWithAppId("****") {[weak self] (result) in
                
                
                main_thread_execute {
                    self?.start(agreePrivacyValue: f)
                }
            }
            
        }).disposed(by: rx.disposeBag)
        
        
        GlobalPresent(toController: licenceVC, animated: true)
        
        
    }
    
    private func reload_with_start_display_link(){
        
        
        collectionView.reloadData {
            self.link = CADisplayLink.init(target: self, selector: #selector(self.scrollAutomatically))
            self.link?.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
        }
        
    }
    
    fileprivate func start(agreePrivacyValue:Bool){
        
        self.agreePrivacy = agreePrivacyValue
        
        print("采集用户设备信息 闪验 start")
        back_thread_execute(afterDelay: 1) {
            ST_RegisterMonitor.shared.logger.report(fromController: self)
        }
        Observable.zip(TIANSession(requestUrl: PH.featureExampleListApi).wrap_response_data().retry(), SCComponets.location_component.city_observer.compactMap({ $0 })).withUnretained(self).subscribe { own,arg in
            
            let json = arg.0
            
            let city = arg.1
            
            if let list = [ST_ExampleTraitCellModel].deserialize(from: json["data"].rawString() ?? "" ) as? [ST_ExampleTraitCellModel]{
                
                own.sourceArray = list
                
                own.sourceArray.forEach { (m) in
                    m.figure_out_param(city: city)
                }
            }
            
            own.data_array = own.sourceArray
            
            own.reload_with_start_display_link()
            
        }.disposed(by: rx.disposeBag)
        
        
        CLShanYanSDKManager.preGetPhonenumber { (result) in
            
            if let error = result.error{
                
                print("SimilarLogin 使用手机号登录 闪验失败：",error)
                
                main_thread_execute {
                    
                    self.pageName = "NoFlashRegistOrLoginType"
                    
                    self.layout_normal_login_views(agreePrivacyValue: agreePrivacyValue)
                    
                }
                
#if DEBUG
                
                main_thread_execute(afterDelay: 3) {
                    ST_RegisterMonitor.shared.set_up_test_btn()
                }
#endif
                
            }else{
                
                main_thread_execute {
                    
                    self.isNormalLogin = false
                    
                    self.pageName = "GotFlashRegistOrLoginType"
                    
                    self.layout_logo_view(logoBottomConstraint: 241+22+6+10+BTSafeAreaBottom)
                    
                    let uiConfigure = ST_ShanYanConfigureMaker(delegate: self).configure_style_yin_ke(configureInstance: CLUIConfigure(),  agreePrivacy: agreePrivacyValue)
                    
                    uiConfigure.viewController = self
                    
                    CLShanYanSDKManager.setCLShanYanSDKManagerDelegate(self)
                    
                    CLShanYanSDKManager.quickAuthLogin(with: uiConfigure, openLoginAuthListener: self.openLoginAuthListener(complete:),oneKeyLoginListener:self.oneKeyLoginListener(complete:))
#if DEBUG
                    
                    main_thread_execute(afterDelay: 3) {
                        ST_RegisterMonitor.shared.set_up_test_btn()
                    }
#endif
                }
            }
            
        }
        
    }
    
    
    fileprivate var isNormalLogin = true
    
    /**
     不使用闪验UI
     */
    fileprivate func layout_normal_login_views(agreePrivacyValue:Bool){
        
        layout_logo_view(logoBottomConstraint: 213+22+6+BTSafeAreaBottom)
        
        view.addSubview(start_btn)
        start_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(content_label.snp.bottom).offset(20)
            make.width.equalTo(260)
            make.height.equalTo(48)
        }
        
        start_btn.addSubview(awardIconImageView)
        awardIconImageView.snp.makeConstraints { (make) in
            make.right.top.equalToSuperview()
            make.height.equalTo(46/2.0)
            make.width.equalTo(120/2.0)
        }
        
        view.addSubview(otherWayLabel)
        otherWayLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(start_btn.snp.bottom).offset(10)
            make.height.equalTo(20)
        }
      
        
        view.addSubview(privacyBottomView)
        privacyBottomView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.height.equalTo(44)
            make.top.equalTo(otherWayLabel.snp.bottom).offset(30+48)
        }
        //        privacyBottomView.backgroundColor = .random
        
        privacyBottomView.addSubview(privacyView)
        privacyView.snp.makeConstraints { (make) in
            make.right.centerY.equalToSuperview()
            //            make.top.equalTo(thridWayBtnView.snp.bottom).offset(10)
        }
        
        
        privacyBottomView.addSubview(agreePrivacyControl)
        agreePrivacyControl.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.width.height.equalTo(44)
            make.left.equalToSuperview()
            make.right.equalTo(privacyView.snp.left).offset(12)
        }
        
        agreePrivacyControl.isSelected = agreePrivacyValue
        
    }
    
    
    fileprivate func layout_logo_view(logoBottomConstraint:CGFloat){
        
        
        
        view.addSubview(logoImageView)
        logoImageView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-logoBottomConstraint)
            make.width.equalTo(66)
            make.height.equalTo(58)
        }
        
        view.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(logoImageView.snp.bottom).offset(6)
            //            make.width.equalTo(190)
            make.height.equalTo(22)
        }
    }
    
    @objc fileprivate func agree_privacy_changed_handle(){
        
        agreePrivacyControl.isSelected = !agreePrivacyControl.isSelected
        
        agreePrivacy = agreePrivacyControl.isSelected
    }
    
    //    MARK: - Properties
    fileprivate lazy var licenceVC:ST_BTLicenceController = {
        let vc = ST_BTLicenceController(nibName: nil, bundle: nil)
        
        return vc
    }()
    
    fileprivate lazy var start_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.cornerRadius = 48/2.0
        control.backgroundColor = UIColor.init(hex: 0xFEC207)
        control.setTitleForAllStates("手机号登录注册")
        control.setTitleColorForAllStates(UIColor.white)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(phone_number_login_handle), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    fileprivate lazy var awardIconImageView:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("login_award_icon"))
        return control
    }()
    
    
    fileprivate lazy var otherWayLabel:UILabel = {
        let control = UILabel.init()
        control.text = "其他登录方式"
        control.textColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        //        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    
    fileprivate lazy var privacyBottomView:UIView = {
        let control = UIView()
        return control
    }()
    
    
    fileprivate lazy var privacyView = ST_TianPrivacyView()
    
    fileprivate var agreePrivacy:Bool = false
    
    fileprivate lazy var agreePrivacyControl:UIButton = {
        let control = UIButton(type: .custom)
        control.setImage(ST_ImageUtils.imageName("splash_check"), for: .selected)
        control.setImage(ST_ImageUtils.imageName("splash_check_gray"), for: .normal)
        control.addTarget(self, action: #selector(agree_privacy_changed_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var logoImageView:UIImageView = {
        
        let control = UIImageView()
        
        control.image = ST_ImageUtils.imageName("登录_img_logo")
        
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = "伴心-听你的话"
        control.textColor = UIColor.init(hex: 0x000000)
        //        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
        let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = ST_PinterestHomeCellMinimumColumnSpacing
        controlLayout.minimumInteritemSpacing = 10
        controlLayout.sectionInset = UIEdgeInsets.init(top: 15, left: 10, bottom: 0, right: 10)
        return controlLayout
    }()
    
    fileprivate lazy var gradient_view:ST_FWGradientView = {
        let control = ST_FWGradientView()
        //        control.bgLayer.colors = [UIColor.init(white: 1, alpha: 0).cgColor,UIColor.init(white: 1, alpha: 1).cgColor]
        //        control.bgLayer.startPoint = CGPoint(x: 1, y: 0)
        //        control.bgLayer.endPoint = CGPoint(x: 1, y: 1)
        control.bgLayer.startPoint = CGPoint(x: 0.5, y: 0)
        control.bgLayer.endPoint = CGPoint(x: 0.5, y: 0.5)
        control.bgLayer.colors = [UIColor(red: 1, green: 1, blue: 1, alpha: 0).cgColor, UIColor(red: 1, green: 1, blue: 1, alpha: 1).cgColor]
        return control
    }()
    
    fileprivate var incrementY = 0.cgFloat
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = .white
        control.delegate = self
        control.dataSource = self
        control.alwaysBounceVertical = true
        control.isUserInteractionEnabled = false
        control.register(cellWithClass: ST_ExampleTraitCell.self)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    
    
    fileprivate lazy var reqAgreeImageView:UIImageView = {
        let v = UIImageView(image: ST_ImageUtils.imageName("splash_check_tip"))
        v.alpha = 0
        //v.cornerRadius = 5
        return v
    }()
    //    MARK: - Event
    @objc fileprivate func toast_require_agree(){
        
        print("需要同意协议")
        
        guard let topVC = TopmostViewController() else{
            return
        }
        
        if reqAgreeImageView.superview == nil {
            topVC.view.addSubview(reqAgreeImageView)
            
            var centerOffsetX = 0,bottomOffset = -35-BTSafeAreaBottom
            
            if !isNormalLogin {
                centerOffsetX = -46
                bottomOffset = -40-BTSafeAreaBottom
            }
            
            reqAgreeImageView.snp.makeConstraints { make in
                make.centerX.equalToSuperview().offset(centerOffsetX)
                make.bottom.equalToSuperview().offset(bottomOffset)
            }
            
        }else{
            return
        }
        
        reqAgreeImageView.alpha = 1
        
        UIView.animate(withDuration: 0.2, delay: 1.5, options: UIView.AnimationOptions.curveEaseIn) {
            
            self.reqAgreeImageView.alpha = 0
            
        } completion: { f in
            
            self.reqAgreeImageView.removeFromSuperview()
        }
        
    }
    
    
    
    @objc fileprivate func phone_number_login_handle(){
        
        if !self.agreePrivacy{
            
            self.toast_require_agree()
            
            return
        }
        
        ST_BTGlobalDataCenter.shared.signInMemberPage(paramValue: "手机号")
        
        ST_RegisterMonitor.shared.from_navigation_controller?.pushViewController(ST_BTPhoneNumberController())
        
    }
    
    
    //    MARK:- SetUp Data
    fileprivate var data_array = [ST_ExampleTraitCellModel]()
    
    fileprivate lazy var sourceArray = [ST_ExampleTraitCellModel]()
    
    fileprivate var link:CADisplayLink?
    
}

//MARK: - Collection Delegate
extension ST_SimilarLoginViewController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        
        let m = data_array[indexPath.row]
        
        return CGSize.init(width: ST_PinterestHomeCellImageWidth, height: m.cellHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_ExampleTraitCell.self, for: indexPath)
        
        if let m = data_array[safe:indexPath.item]{
            cell.model = m
        }
        return cell
    }
    
    
    @objc func scrollAutomatically() {
        
        
        if self.data_array.count < 1{
            return
        }
        
        
        
        if collectionView.indexPathsForVisibleItems.contains(IndexPath.init(row: self.data_array.count-1, section: 0)){
            
            self.link?.invalidate()
            self.link = nil
            
            return
        }
        
        
        incrementY += 1.5/3.0
        
        collectionView.setContentOffset(CGPoint.init(x: 0, y: incrementY), animated: false)
        
        
    }
    
}

//MARK: - Shanyan Delegate
extension ST_SimilarLoginViewController:CLShanYanSDKManagerDelegate,ST_ShanYanConfigureMakerDelegate{
    
    func clShanYanActionListener(_ type: Int, code: Int, message: String?) {
        
        if type == 2 {
            agreePrivacy = code == 1
        }
        
    }
    
    func clShanYanSDKManagerAuthPageCompleteViewDidLoad(_ authPageVC: UIViewController, currentTelecom telecom: String?, object: NSObject?, userInfo: [AnyHashable : Any]? = nil) {
        
        ST_RegisterMonitor.shared.from_navigation_controller = authPageVC.navigationController
        
    }
    
    
    func clShanYanSDKManagerAuthPageCompleteViewWillAppear(_ authPageVC: UIViewController, currentTelecom telecom: String?, object: NSObject?, userInfo: [AnyHashable : Any]? = nil) {
        
    }
    
    
    func openLoginAuthListener(complete: CLCompleteResult){
        
        //        DispatchQueue.main.async {
        //            HUD.hide()
        //        }
        
        let error = complete.error as NSError?
        guard error == nil else{
            let msg = String(complete.code)
            let message = complete.message ?? ""
            var errorString = ""
            if error!.userInfo.count > 0 {
                errorString = String(format: "%@", JSON(error!.userInfo).dictionaryObject ?? "")
            }
            
            print(#function,#line,msg,message,errorString)
            
            print("SimilarLogin 闪验打开成功")
            
            return
        }
        
        print(#function,#line,complete.code,complete.message ?? "")
    }
    
    
    
    func oneKeyLoginListener(complete: CLCompleteResult){
        
        
        print(#function,#line,complete.code,complete.message ?? "")
        
        guard let token = complete.data?["token"] as? String else {
            return
        }
        
        main_thread_execute {
            
            self.loginUseShanyan(sToken: token)
        }
        
        
        
    }
    
    fileprivate func loginUseShanyan(sToken:String)  {
        
        print("SimilarLogin 闪验token:",sToken)
        
        ST_BTGlobalDataCenter.shared.signInMemberPage(paramValue: "本机号码一键登录")
        
        ST_RegisterMonitor.shared.get_started(dict: ["open_id":sToken,"type":"4"], expectedHudController: self)
        
    }
    
    func shanYanConfigureOtherWayClick(sender: UIButton){
        
        print("SimilarLogin 闪验其他登录方式")
        
        main_thread_execute {
            
            if !self.agreePrivacy{
                
                self.toast_require_agree()
                
                return
            }
            
            ST_RegisterMonitor.shared.from_navigation_controller?.pushViewController(ST_BTPhoneNumberController())
        }
        
        
    }
    
    func custom_nav_left_item_click(sender: UIButton){
        
    }
    
}
